package com.elitetyc.eliteim.client.handler;

import com.elitetyc.eliteim.common.handler.RequestMsgHandler;
import com.elitetyc.eliteim.common.proto.RequestProto;
import com.elitetyc.eliteim.common.util.SpringBeanFactory;
import com.elitetyc.eliteim.client.EliteIMClient;
import com.elitetyc.eliteim.client.service.ReConnectService;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description TODO
 * @Date 2021/9/16 10:30
 */
@SuppressWarnings({"unchecked","rawtypes"})
@Component
@Slf4j
@ChannelHandler.Sharable
public class ClientChannelInBoundHandler extends SimpleChannelInboundHandler<RequestProto.RequestProtocol> {

    @Autowired
    private List<RequestMsgHandler> requestMsgHandlers;

    @Autowired
    private RequestProto.RequestProtocol ping;

    @Autowired
    private EliteIMClient eliteIMClient;

    @Autowired
    private ReConnectService reConnectService;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestProto.RequestProtocol msg) throws Exception {
        boolean handled = false;
        for (RequestMsgHandler msgHandler : requestMsgHandlers) {
            if (msgHandler.support(msg.getType())) {
                msgHandler.handleMsg(ctx, msg, msgHandler.convertProto2Msg(msg));
                handled = true;
            }
        }
        if (!handled) {
            log.warn("no handler handled msg");
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            final IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                // 如果用户未主动发送消息，为了保持连接，发送一次心跳包
                ctx.channel().writeAndFlush(ping).addListeners((ChannelFutureListener) future -> {
                    if (!future.isSuccess()){
                        log.error("ping server error!");
                        future.channel().close();
                    }
                });
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("im client connect server success");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("im client disconnect server");
        eliteIMClient.clearSocket(ctx.channel());
        reConnectService.reConnect();
    }


}
